//
//  VipVC.m
//  Brand
//
//  Created by Faker on 5/21/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "VipVC.h"
#import "VipObj.h"
#import "AlixLibService.h"
#import "Header.h"


@interface VipVC ()
@property (strong, nonatomic) IBOutlet UIView *navTopContentView;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSMutableArray* dataArray;
@property (strong, nonatomic) IBOutlet UIView *popView;
@property (strong, nonatomic) IBOutlet UIView *popMaskView;

@property (strong, nonatomic) NSTimer* mTimer;

@property (strong, nonatomic) VipObj* currentVipObj;

@end

@implementation VipVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [Common handleHeightWithIPhone5WithView:self.view];
    // Do any additional setup after loading the view from its nib.
    [self drawNavTopContentView:self.navTopContentView];
   
    [self setUp];
}

-(void)setUp
{
    self.dataArray = [[NSMutableArray alloc]init];
    [[[NSBundle mainBundle]loadNibNamed:@"PopCell" owner:self options:nil] lastObject];
    self.popView.layer.cornerRadius = 5;
    self.popView.clipsToBounds = YES;
    self.popView.left = (self.view.width-self.popView.width)/2;
    self.popView.top = (self.view.height - self.popView.height)/2;
    
    UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popViewIn)];
    [self.popMaskView addGestureRecognizer:ges];
    
    [InAppPurchase sharedInstance].delegate = self;
    [self prepareGetData];
}


#pragma mark - 网络请求
-(void)prepareGetData
{
    [kApp displayWaitViewWithAllMaskView:NO];
    
    
    NSString* url = [NSString stringWithFormat:@"%@getVipItem&pf=2",API_BASE];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getDataSuccess:responseObj];
        }
        else{
            [self getDataError];
        }
    }];
}

-(void)getDataSuccess:(id)responseObj
{
    [kApp hideWaitView];
    
    NSArray* tempArray = (NSArray*)responseObj;
    for (NSDictionary* dic in tempArray) {
        VipObj* vipObj = [[VipObj alloc]init];
        vipObj.mId = [dic objectForKey:@"id"];
        vipObj.title = [dic objectForKey:@"title"];
        vipObj.days = [dic objectForKey:@"days"];
        vipObj.info = [dic objectForKey:@"v_desc"];
        vipObj.price = [dic objectForKey:@"v_price"];
        vipObj.isFree = [dic objectForKey:@"is_free"];
        vipObj.itemId = [dic objectForKey:@"item_id"];
        [self.dataArray addObject:vipObj];
    }
    
    [self.myTableView reloadData];
}

-(void)getDataError
{
    [kApp hideWaitView];
    [PopTips tips:self.view Msg:NotifyNoNet];
    [self performSelector:@selector(goBack:) withObject:self afterDelay:0.7];
}

#pragma mark - UITableView  methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"identifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil)
    {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"VipCell" owner:self options:nil]lastObject];
    }
    
    VipObj* vipObj = [self.dataArray objectAtIndex:indexPath.row];
    
    UILabel* titleLabel = (UILabel*)[cell viewWithTag:200];
    UILabel* infoLabel = (UILabel*)[cell viewWithTag:202];
    UILabel* priceLabel = (UILabel*)[cell viewWithTag:203];
    UIImageView* imageView = (UIImageView*)[cell viewWithTag:301];
    
    if([vipObj.isFree isEqualToString:@"1"])
    {
        imageView.hidden = NO;
    }
    else{
        imageView.hidden = YES;
    }
    
    titleLabel.text = vipObj.title;
    [Common handleTheLabelHeight:infoLabel withText:vipObj.info];
    priceLabel.text = vipObj.price;
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 66;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.currentVipObj = [self.dataArray objectAtIndex:indexPath.row];
    
    if (![self isLoginIn]) { //没有登陆的才返回
        return;
    }
    
//    if ([kHandle sharedInstance].isShowTrueView) {
//        [self popViewOut];
//    }else{
//        [[InAppPurchase sharedInstance] getVIP:self.currentVipObj.mId];
//    }
    
    [self aliPay:nil];
    
}

-(BOOL)isLoginIn{
    if([[UserObj sharedInstance] isLegalLogin]){
        return YES;
    }else{
        [PopTips tips:self.view Msg:NotifyLoginFirst];
        return NO;
    }
}



#pragma mark - 弹层
-(void)popViewOut
{
    [self.view addSubview:self.popMaskView];
    [self.view addSubview:self.popView];
    
    self.popMaskView.alpha= 0;
    self.popView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    self.popView.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        self.popMaskView.alpha = 0.5;
        self.popView.alpha = 1;
        self.popView.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            self.popView.transform = CGAffineTransformMakeScale(1.0, 1.0);
        }];
    }];
}

-(void)popViewIn
{
    [kApp hideWaitView];
    [UIView animateWithDuration:0.2 animations:^{
        self.popView.alpha = 0;
        self.popMaskView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.popMaskView removeFromSuperview];
        [self.popView removeFromSuperview];
    }];
}

-(void)InAppPurchaseSccessOrNot:(BOOL)isSuccess{
    if (self.popMaskView.superview) {
        [self popViewIn];
    }
}

#pragma mark - xib点击事件

- (IBAction)iPAPay:(id)sender {
    [[InAppPurchase sharedInstance] getVIP:self.currentVipObj.mId];
}


#pragma mark - 支付宝
- (IBAction)aliPay:(id)sender {
//    [self popViewIn];
    
    if([[UserObj sharedInstance] uid]&&[[UserObj sharedInstance] accessKey])
    {
       NSString* url = @"http://kuiba.haomee.net/?m=Alipay&a=createVipOrder";
      [[AFGetData sharedInstance] startPost:url andInfo:@{@"uid": [[UserObj sharedInstance] uid],@"ak":[[UserObj sharedInstance] accessKey],@"itemId":self.currentVipObj.mId,@"pf":@"2",@"type":@"1"} andDataBodyBlock:^(id<AFMultipartFormData> formData) {
      
    } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self goSuccess:responseObj];
        }
        else
        {
            [self goError];
        }
    }];
    }
}

-(void)goSuccess:(id)responseObj
{
   
    NSDictionary* dic = (NSDictionary*)responseObj;
    NSString* orderString = [dic objectForKey:@"data"];
    [AlixLibService payOrder:orderString AndScheme:@"kuiba" seletor:@selector(resultSuccess:) target:self];
}

-(void)goError
{
    
}

//没有安装支付宝客户端的情况下
-(void)resultSuccess:(NSString*)result
{
    
    NSArray* stringArray = [result componentsSeparatedByString:@";"];
    NSString* tempString = [stringArray objectAtIndex:0];
    NSString* string1 = [tempString substringFromIndex:14];
    NSString* string2 = [string1 substringToIndex:string1.length-1];
    
   
    if([string2 isEqualToString:@"9000"])
    {
        
        NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleSuccess
                                                          title:NotifyTitlSuceess
                                                        message:NotifyVipSuccess
                                                       delegate:nil];
        [alert show];
        
    }
    else{
        
        NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError
                                                          title:NotifyNormal
                                                        message:NotifyVipError
                                                       delegate:nil];
        [alert show];
    }
}

#pragma mark - 动画
-(CATransition *)createAnimationWithType:(id)type andSubType:(id)subType andur:(float )dur andDelegate:(id)delegate{
    CATransition *animation = [CATransition animation];
    [animation setDuration:dur];
    [animation setType: type];
    animation.subtype = subType;
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setDelegate:delegate];
    return animation;
    
}



- (IBAction)goBack:(id)sender {
    [self.mTimer invalidate];
    [kApp hideWaitView];
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
